package com.dgut.usermodule.web;

import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dgut.common.util.SessionUtil;
import com.dgut.usermodule.entity.User;
import com.dgut.usermodule.service.UserService;

@RestController
@CrossOrigin
public class LoginCtrl {
	/**
	 * 登陆入口
	 * @param username
	 * @param password
	 * @return
	 */
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login")
	public  String login(@RequestParam("username") String username,@RequestParam("password") String password,HttpSession session) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated() == false) {
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			try {
				User user = userService.findByName(username);
				if (user!=null) {
					SessionUtil.setUser(session, user);
				}
				
				currentUser.login(token);
			} catch (AuthenticationException e) {
				throw new UnauthenticatedException();
			}
		}
		return "true";
	}
	@RequestMapping("/getUsername")
	public  String getUsername() {
		String userName = (String)SecurityUtils.getSubject().getPrincipal();
		return userName;
	}
	
	@RequestMapping("/deleteSession")
	public  void deleteSession(HttpSession session) {
		SessionUtil.removeAttribute(session);
	}
}
